
<template>
    <el-upload
        class="upload-demo"
        ref="upload"
        :action="$attrs.action"
        :data="$attrs.data"
        :headers="headers"
        :before-upload="handleBeforeUpload"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :show-file-list="false"
    >
        <el-button slot="trigger" :type="type" :loading="loading" :disabled="loading">{{ text }}</el-button>
    </el-upload>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
    name: 'UploadButton',
    props: {
        text: {
            type: [String, undefined, null],
            default: '上传文件'
        },
        type: {
            type: String,
            default: 'success'
        }
    },
    data() {
        return {
            headers: {
                token: getToken(),
            },
            loading: false,
        }
    },
    methods: {
        handleBeforeUpload() {
            this.loading = true
        },
        handleRemove(file, fileList) {
            console.log(file, fileList)
        },
        handlePreview(file) {
            console.log(file)
        },

        // 上传成功回调
        handleUploadSuccess(res) {
            this.loading = false
            if (res.code == 200) {
                this.$message.success(res.msg)
                this.$emit('success', res)
            } else {
                this.$message.error(res.msg)
                this.$emit('error', res)
            }
            this.$emit('complete', res)
        },
        // 上传失败
        handleUploadError(res) {
            this.loading = false
            this.$message.error('上传失败')
            this.$emit('error', res)
            this.$emit('complete', res)
        },
    },
}
</script>

<style></style>
